package com.eastfair.venueservice.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eastfair.annotation.annotation.log.SysLog;
import com.eastfair.annotation.annotation.security.PreAuth;
import com.eastfair.boot.controller.SuperController;
import com.eastfair.boot.request.PageParams;
import com.eastfair.constant.BusinessConstant;
import com.eastfair.core.base.R;
import com.eastfair.core.context.ContextUtil;
import com.eastfair.echo.core.EchoService;
import com.eastfair.venuebooking.api.ExhibitionSpaceFeign;
import com.eastfair.venuebooking.vo.ExhibitionSpaceVO;
import com.eastfair.venueservice.dto.*;
import com.eastfair.venueservice.entity.ExhibitionManage;
import com.eastfair.venueservice.service.ExhibitionManageService;
import com.eastfair.venueservice.service.ServiceProviderSpaceService;
import com.eastfair.venueservice.service.impl.ServiceProviderSpaceServiceImpl;
import com.eastfair.venueservice.vo.ExhibitionManageVO;
import com.eastfair.venueservice.vo.ExhibitionSpaceSiteVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * 综合服务展会
 * </p>
 *
 * @author linan
 * @date 2022-07-15
 */
@Slf4j
@Validated
@RestController
@RequestMapping("/exhibitionManage")
@Api(value = "ExhibitionManage", tags = "综合服务展会")
@PreAuth(replace = "venueservice:exhibitionManage:")
public class ExhibitionManageController extends SuperController<ExhibitionManageService, Long, ExhibitionManage, ExhibitionManagePageQuery, ExhibitionManageSaveDTO, ExhibitionManageUpdateDTO> {

    @Value("${com.eastfair.projectId}")
    private Long projectId;

    @Autowired
    private EchoService echoService;
    @Resource
    private ExhibitionSpaceFeign exhibitionSpaceFeign;

    @Resource
    private ServiceProviderSpaceService serviceProviderSpaceService;

    @Override
    public void handlerResult(IPage<ExhibitionManage> page) {
        // 想让返回值实现自动回显，请将此行代码打开
        // echoService.action(page);
    }
    /**
     * Excel导入后的操作
     *
     * @param list
     */
    @Override
    public R<Boolean> handlerImport(List<Map<String, String>> list){
        List<ExhibitionManage> exhibitionManageList = list.stream().map((map) -> {
            ExhibitionManage exhibitionManage = ExhibitionManage.builder().build();
            //TODO 请在这里完成转换
            return exhibitionManage;
        }).collect(Collectors.toList());

        return R.success(baseService.saveBatch(exhibitionManageList));
    }



    /**
     * 处理参数
     *
     * @param params 分页参数
     */
    @Override
    public void handlerQueryParams(PageParams<ExhibitionManagePageQuery> params) {
        ExhibitionManagePageQuery pageQuery = params.getModel();
        //分页处理
        if(ContextUtil.getProjectId()!=null){
            pageQuery.setProjectId(ContextUtil.getProjectId());
        }
    }

    /**
     * 更新展会（综合）
     *
     * @param exhibitionDTO 更新展会（综合）
     * @return R
     */
    @ApiOperation(value = "更新展会（综合）", notes = "更新展会（综合）")
    @SysLog("修改展会")
    @PostMapping("/updateExhibitionManage")
    public R<Boolean> updateExhibitionManage(@RequestBody @Validated(ExhibitionManageDTO.Update.class) ExhibitionManageDTO exhibitionDTO) {
        log.info("updateExhibitionManage - 更新展会（综合） exhibitionDTO={}", exhibitionDTO);
        return baseService.updateExhibitionManage(exhibitionDTO);
    }

    /**
     * 查询展会列表（综合）
     *
     * @param exhibitionManageQuery 查询展会列表（综合）
     * @return R
     */
    @ApiOperation(value = "查询展会列表（综合）", notes = "查询展会列表（综合）")
    @PostMapping("/queryExhibitionManage")
    public R<IPage<ExhibitionManageVO>> queryExhibitionManage(@RequestBody PageParams<ExhibitionManageQuery> exhibitionManageQuery) {
        log.info("queryExhibitionManage - 查询展会列表（综合） exhibitionManageQuery={}", exhibitionManageQuery);
        return baseService.queryExhibitionManage(exhibitionManageQuery);
    }

    /**
     * 查询展会详情
     *
     * @param exhibitionManageQuery 查询展会详情
     * @return R
     */
    @ApiOperation(value = "查询展会详情", notes = "查询展会详情")
    @PostMapping("/queryExhibitionManageDetail")
    public R<ExhibitionManageVO> queryExhibitionManageDetail(@RequestBody ExhibitionManageQuery exhibitionManageQuery) {
        log.info("queryExhibitionManageDetail - 查询展会详情 exhibitionManageQuery={}", exhibitionManageQuery);
        PageParams pageParams = new PageParams();
        pageParams.setModel(exhibitionManageQuery);
        pageParams.setCurrent(0);
        pageParams.setSize(1);
        return baseService.queryExhibitionManageDetail(pageParams);
    }

    /**
     * 通过服务商查询进行中的展会
     *
     * @param exhibitionManageQuery 通过服务商查询进行中的展会
     * @return R
     */
    @ApiOperation(value = "通过服务商查询进行中的展会", notes = "通过服务商查询进行中的展会")
    @PostMapping("/queryExhibitionManageByProvider")
    public R<ExhibitionManageVO> queryExhibitionManageByProvider(@RequestBody ExhibitionManageQuery exhibitionManageQuery) {
        log.info("queryExhibitionManageByProvider - 通过服务商查询进行中的展会 exhibitionManageQuery={}", exhibitionManageQuery);
        return baseService.queryExhibitionManageByProvider(exhibitionManageQuery);
    }

    /**
     * 查询展会下拉列表（综合）
     *
     * @param exhibitionManageQuery 查询展会下拉列表（综合）
     * @return R
     */
    @ApiOperation(value = "查询展会下拉列表（综合）", notes = "查询展会下拉列表（综合）")
    @PostMapping("/queryAllExhibitionManage")
    public R<List<ExhibitionManageVO>> queryAllExhibitionManage(@RequestBody ExhibitionManageQuery exhibitionManageQuery) {
        log.info("queryAllExhibitionManage - 查询展会列表（综合） exhibitionManageQuery={}", exhibitionManageQuery);
        return baseService.queryAllExhibitionManage(exhibitionManageQuery);
    }

    /**
     * 外部系统查询展会列表
     *
     * @param exhibitionManageQuery query
     * @return R
     */
    @ApiOperation(value = "外部系统查询展会列表", notes = "外部系统查询展会列表")
    @PostMapping("/queryAllExhibitionManageForExternal")
    public R<List<ExhibitionManageVO>> queryAllExhibitionManageForExternal(@RequestBody ExhibitionManageQuery exhibitionManageQuery) {
        log.info("queryAllExhibitionManageForExternal - 外部系统查询展会列表  exhibitionManageQuery={}", exhibitionManageQuery);
        ContextUtil.setProjectId(projectId);
        return baseService.queryAllExhibitionManage(exhibitionManageQuery);
    }

    /**
     * 查询展会列表（综合）外部
     *
     * @param exhibitionManageQuery 查询展会列表（综合）外部
     * @return R
     */
    @ApiOperation(value = "查询展会列表（综合）外部", notes = "查询展会列表（综合）外部")
    @PostMapping("/queryExhibitionManageForExternal")
    public R<IPage<ExhibitionManageVO>> queryExhibitionManageForExternal(@RequestBody PageParams<ExhibitionManageQuery> exhibitionManageQuery) {
        log.info("queryExhibitionManage - 查询展会列表（综合）外部 exhibitionManageQuery={}", exhibitionManageQuery);
        ContextUtil.setProjectId(projectId);
        return baseService.queryExhibitionManage(exhibitionManageQuery);
    }

    /**
     * 同步展会
     *
     * @param exhibitionManageDTO exhibitionManageDTO
     * @return the r
     */
    @ApiOperation(value = "同步展会", notes = "同步展会")
    @SysLog("同步展会")
    @PostMapping("/syncExhibition")
    public R<Boolean> syncExhibition(@RequestBody ExhibitionManageDTO exhibitionManageDTO){
        ExhibitionManage exhibitionManage = baseService.getOne(new QueryWrapper<ExhibitionManage>().lambda ().eq(ExhibitionManage::getIsDeleted, BusinessConstant.NO).eq(ExhibitionManage::getVbExhibitionId,exhibitionManageDTO.getVbExhibitionId()));
        if(Objects.nonNull(exhibitionManage)){
            UpdateWrapper<ExhibitionManage> wrapper = new UpdateWrapper<>();
            packageWrapper(exhibitionManageDTO, exhibitionManage, wrapper);
            return R.success(baseService.update(wrapper));
        }else {
            ExhibitionManage manage = new ExhibitionManage();
            BeanUtils.copyProperties(exhibitionManageDTO,manage,"id","isEnabled","createTime");
            manage.setIsEnabled(BusinessConstant.NO);
            return R.success(baseService.save(manage));
        }
    }

    /**
     * 封装wrapper
     * @param exhibitionManageDTO exhibitionManageDTO
     * @param exhibitionManage exhibitionManage
     * @param wrapper wrapper
     */
    private void packageWrapper(ExhibitionManageDTO exhibitionManageDTO, ExhibitionManage exhibitionManage, UpdateWrapper<ExhibitionManage> wrapper) {
        wrapper.lambda().eq(ExhibitionManage::getVbExhibitionId, exhibitionManage.getVbExhibitionId())
                .set(ExhibitionManage::getExhibitionNo, exhibitionManageDTO.getExhibitionNo())
                // 展会名称
                .set(ExhibitionManage::getExhibitionName, exhibitionManageDTO.getExhibitionName())
                // 主办
                .set(ExhibitionManage::getSponsorName, exhibitionManageDTO.getSponsorName())
                // 使用面积
                .set(ExhibitionManage::getReserveArea, exhibitionManageDTO.getReserveArea())
                // 行业属性
                .set(ExhibitionManage::getIndustry, exhibitionManageDTO.getIndustry())
                // 展览时间
                .set(ExhibitionManage::getExhibitionStartTime, exhibitionManageDTO.getExhibitionStartTime())
                .set(ExhibitionManage::getExhibitionEndTime, exhibitionManageDTO.getExhibitionEndTime())
                .set(ExhibitionManage::getArrangementStartTime, exhibitionManageDTO.getArrangementStartTime())
                .set(ExhibitionManage::getArrangementEndTime, exhibitionManageDTO.getArrangementEndTime())
                .set(ExhibitionManage::getDismantlingStartTime, exhibitionManageDTO.getDismantlingStartTime())
                .set(ExhibitionManage::getDismantlingEndTime, exhibitionManageDTO.getDismantlingEndTime())
                // 英文名称
                .set(ExhibitionManage::getExhibitionEnName, exhibitionManageDTO.getExhibitionEnName())
                // 展会简称
                .set(ExhibitionManage::getExhibitionShortName, exhibitionManageDTO.getExhibitionShortName())
                // 展会网址
                .set(ExhibitionManage::getExhibitionWebsite, exhibitionManageDTO.getExhibitionWebsite())
                // 英文简称
                .set(ExhibitionManage::getExhibitionEnShortName, exhibitionManageDTO.getExhibitionEnShortName())
                // LOGO
                .set(ExhibitionManage::getLogoUrl, exhibitionManageDTO.getLogoUrl())
                // 展会介绍
                .set(ExhibitionManage::getRemark, exhibitionManageDTO.getRemark());
    }



    /**
     * 展会ID查询展会场地
     *
     * @param exhibitionManageId exhibitionManageId
     * @return the r
     */
    @GetMapping("/querySpaceByExhibitionManageId")
    public R<List<ExhibitionSpaceVO>> querySpaceByExhibitionManageId(@RequestParam(value = "exhibitionManageId") Long exhibitionManageId,
                                                                     @RequestParam(value = "serviceProviderId", required = false) Long serviceProviderId) {
        ExhibitionManage exhibitionManage = baseService.getById(exhibitionManageId);
        if (Objects.nonNull(exhibitionManage)) {
            if (serviceProviderId == null) {
                return exhibitionSpaceFeign.queryByExhibitionId(exhibitionManage.getVbExhibitionId());
            } else {
                return R.successDef(serviceProviderSpaceService.queryExhibitionSpaceByExhibitionId(exhibitionManageId, serviceProviderId));
            }
        } else {
            return R.fail("未找到对应展会");
        }
    }



    /**
     * 展会ID查询展会场地
     *
     * @param exhibitionManageId exhibitionManageId
     * @return the r
     */
    @GetMapping("/queryServiceProviderSpace")
    public R<List<ExhibitionSpaceVO>> queryServiceProviderSpace(@RequestParam(value = "exhibitionManageId") Long exhibitionManageId,@RequestParam(value = "serviceProviderId") Long serviceProviderId) {
        ExhibitionManage exhibitionManage = baseService.getById(exhibitionManageId);
        if(Objects.nonNull(exhibitionManage)){
            return baseService.querySpaceByExhibitionManageId(exhibitionManage,serviceProviderId);
        }else {
            return R.fail("未找到对应展会");
        }
    }

    /**
     * 展会ID查询展会场地
     *
     * @param exhibitionManageId the exhibition id
     * @return the r
     */
    @GetMapping("/exhibition/{exhibitionManageId}")
    public R<List<ExhibitionSpaceVO>> queryByExhibitionManageId(@PathVariable("exhibitionManageId") Long exhibitionManageId) {
        ExhibitionManage exhibitionManage = baseService.getById(exhibitionManageId);
        if(Objects.nonNull(exhibitionManage)){
            return exhibitionSpaceFeign.queryByExhibitionId(exhibitionManage.getVbExhibitionId());
        }else {
            return R.fail("未找到对应展会");
        }
    }

    /**
     * 查询展会的展厅和展位.
     *
     * @param exhibitionManageId the exhibition manage id
     * @return the r
     */
    @GetMapping("/space/site/{exhibitionManageId}")
    public R<List<ExhibitionSpaceSiteVO>> querySpaceSiteByExhibitionManageId(@PathVariable("exhibitionManageId") Long exhibitionManageId) {
        log.info("querySpaceSiteByExhibitionManageId - 查询展会的展厅和展位, exhibitionManageId={}", exhibitionManageId);
        return R.successDef(baseService.querySpaceSiteByExhibitionManageId(exhibitionManageId));
    }

    /**
     * 展会概述
     *
     * @param exhibitionManageId the exhibition id
     * @return the r
     */
    @GetMapping("queryExhibitionSummary")
    public R<Map<String,Object>> queryExhibitionSummary(@RequestParam(value = "exhibitionManageId") Long exhibitionManageId) {
        ExhibitionManage exhibitionManage = baseService.getById(exhibitionManageId);
        if(Objects.nonNull(exhibitionManage)){
            return R.success(baseService.queryExhibitionSummary(exhibitionManage));
        }else {
            return R.fail("未找到对应展会");
        }
    }

    /**
     * 查询展会未同步的所有展会
     *
     * @return R
     */
    @ApiOperation(value = "查询展会未同步的所有展会", notes = "查询展会未同步的所有展会")
    @PostMapping("/queryNeedSyncExhibitionManage")
    public R<List<ExhibitionManageVO>> queryNeedSyncExhibitionManage() {
        log.info("queryNeedSyncExhibitionManage - 查询展会未同步的所有展会");
        return R.success(baseService.queryNeedSyncExhibitionManage());
    }

    /**
     * 查询最近的展会列表.
     *
     * @param pageParams the page params
     * @return the r
     */
    @PostMapping("query/latest/exhibition")
    public R<Page<ExhibitionManageVO>> queryLatestExhibitionManage(@RequestBody PageParams<ExhibitionManageDTO> pageParams) {
        log.info("queryLatestExhibitionManage - 查询近期开展的展会列表, pageParams={}", pageParams);
        return R.successDef(baseService.listLatestExhibition(pageParams));
    }

    /**
     * 展会同步回调
     *
     * @return R
     */
    @ApiOperation(value = "展会同步回调", notes = "展会同步回调")
    @PostMapping("/syncCallback")
    public R<Boolean> syncCallback(@RequestBody List<Long> ids) {
        log.info("syncCallback - 展会同步回调");
        return R.success(baseService.syncCallback(ids));
    }
}
